import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:tracker/common/widget/common.dart';

import '../../../../common/constants/app_constants.dart';
import '../../../../common/log/x_logger.dart';
import 'package:tracker/common/model/base_resp.dart';
import '../../../../provider/global_provider.dart';
import '../../../../router/router_manager.dart';
import '../../../../theme/app_theme.dart';
import '../../../../utils/toast_utils.dart';
import '../../record_history/model/device_details_resp.dart';
import '../../record_history/model/read_file_resp.dart';
import '../../setting/model/get_setting_resp.dart';
import '../../setting/model/remote_setting_list_resp.dart';
import '../mixin/work_mode_mixin.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:tracker/pages/home/setting/dialog/command_dialog_interface.dart';

class WorkModePage extends ConsumerStatefulWidget {
  const WorkModePage({super.key});

  @override
  ConsumerState<WorkModePage> createState() => _WorkModePageState();
}

class _WorkModePageState extends ConsumerState<WorkModePage>
    with LocationModeMixin {
  bool hasData = false;
  RemoteSettingData? remoteSettingData;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      XLogger.info("addPostFrameCallback");
      getDeviceInfo();
    });
    super.initState();
   }

  void getDeviceInfo() async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    final res = await get<DeviceDetailsResp, DeviceDetailsResp>(
        '$newBaseULr/device/${deviceInfo.imei}',
        decodeType: DeviceDetailsResp());
    res.when(success: (resp) {
      setState(() {
        deviceDetails = resp.data;
      });
      _getUserSetting('nmset');
    }, failure: (String msg, int code) {
      XLogger.error('获取设备信息失败：msg: $msg, code: $code');
      deviceDetails = DeviceDetails();
      setState(() {
        loadOver = true;
      });
    });
  }


  _getUserSetting(String cmdCode) async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    final postData = {
      'imei': deviceInfo.imei,
      'cmdCode': cmdCode,
    };
    final res =
    await post<GetSettingResp, GetSettingResp>('/command/getSetting', data: postData, decodeType: GetSettingResp());
    res.when(success: (resp) {
      if (resp.code == 200) {
        updateCmdContent(resp.data?.cmdContent ?? '');

      } else {
        updateCmdContent(resp.data?.cmdContent ?? '');
        ToastUtils.showToast(resp.msg ?? '获取用户指令配置失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('获取用户指令配置失败: msg: $msg, code: $code');
      ToastUtils.showToast('获取用户指令配置失败: msg: $msg, code: $code');
      setState(() {
        loadOver = true;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    final deviceInfo = ref.watch(deviceInfoProvider);
    if (loadOver == false) {
      return Container(
        alignment: Alignment.center,
        child: CircularProgressIndicator(
          color: AppTheme.themeConfig.primaryColor,
        ),
      );
     }
    return Scaffold(
        appBar: AppBar(
          title: const Text('定位模式', style: TextStyle(fontSize: 18)),
          centerTitle: true,
          backgroundColor: AppTheme.themeConfig.navBarColor,
          foregroundColor: AppTheme.themeConfig.primaryColor,
          leading: GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: Container(
              height: kToolbarHeight,
              padding: const EdgeInsets.only(top: 8),
              alignment: Alignment.center,
              child: const Text(' <返回',
                  textAlign: TextAlign.center,
                  maxLines: 1,
                  style: TextStyle(color: Colors.black)),
            ),
          ),
        ),
        backgroundColor: AppTheme.themeConfig.navBarColor,
        body: Container(
          color: Colors.white,
          child: Container(
            padding: const EdgeInsets.only(left: 20, right: 20, top: 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Text(
                //   '工作模式',
                //   style: TextStyle(
                //     fontSize: 18,
                //     color: AppTheme.themeConfig.primaryTextColor,
                //     fontWeight: FontWeight.bold,
                //   ),
                // ),
                // const SizedBox(
                //   height: 20,
                // ),
                Row(
                  children: [
                    Expanded(
                      child:
                      deviceDetails?.positionVip == 1
                          ?
                      Text(
                        '秒定模式（已购买）',
                        style: TextStyle(
                          fontSize: 18,
                          color: AppTheme.themeConfig.primaryColor,
                          fontWeight: FontWeight.bold,
                        ),
                      )
                          :
                      Text(
                        '秒定模式（未开通）',
                        style: TextStyle(
                          fontSize: 18,
                          color: AppTheme.themeConfig.primaryTextColor,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    Radio(
                      value: 3,
                      groupValue: switchValue,
                      onChanged: (value) {
                        XLogger.info('value: $value');
                        if (deviceDetails?.positionVip != 1) {
                          _kaitongmiaoding();
                        }else {
                          setState(() {
                            switchValue = value!;
                          });
                          final data = {
                            "imei": deviceInfo.imei,
                            "positionStatus": "1"
                          };
                          setDevice(data: data,voidCallback:(){
                            onSendCommandClickCallback(getCommand());
                          });
                        }
                      },
                      activeColor: AppTheme.themeConfig.primaryColor,
                    ),
                  ],
                ),
                Row(
                  children: [
                    // 提示语
                    Expanded(
                      child: Text(
                        '每10秒上报定位数据，并开启拐点补偿，数据上报频率更高，耗电量增加，可查询轨迹数据更完整，轨迹更完美。',
                        style: TextStyle(
                          fontSize: 16,
                          color: AppTheme.themeConfig.infoTextColor,
                        ),
                      ),
                    ),
                  ],
                ),
                // 分割线
                const Divider(
                  height: 20,
                  thickness: 1,
                  color: Color(0xffe5e5e5),
                ),
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        '智能模式',
                        style: TextStyle(
                          fontSize: 18,
                          color: AppTheme.themeConfig.primaryTextColor,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    Radio(
                      value: 0,
                      groupValue: switchValue,
                      onChanged: (value) {
                        XLogger.info('value: $value');
                        setState(() {
                          switchValue = value!;
                        });

                        onSendCommandClickCallback(getCommand());
                      },
                      activeColor: AppTheme.themeConfig.primaryColor,
                    ),
                  ],
                ),
                Row(
                  children: [
                    // 提示语
                    Expanded(
                      child: Text(
                        '根据定位间隔更新定位，间隔越长越省电，间隔越短历史轨迹精确度越高。',
                        style: TextStyle(
                          fontSize: 16,
                          color: AppTheme.themeConfig.infoTextColor,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: 12,
                ),
                Row(
                  children: [
                    Text(
                      '定位间隔: ',
                      style: TextStyle(fontSize: 16, color: AppTheme.themeConfig.primaryTextColor),
                    ),
                    GestureDetector(
                        onTap: () {
                          // 显示picker
                          Picker picker = Picker(
                            adapter: PickerDataAdapter(
                              data: modeOptions1.map((e) => PickerItem(text: Text(e.label), value: e.value)).toList(),
                            ),
                            changeToFirst: true,
                            cancelText: '取消',
                            confirmText: '确定',
                            cancelTextStyle: const TextStyle(color: Colors.grey, fontSize: 16),
                            textAlign: TextAlign.left,
                            textStyle: const TextStyle(color: Colors.black, fontSize: 18),
                            selectedTextStyle: TextStyle(color: AppTheme.themeConfig.primaryColor, fontSize: 18),
                            columnPadding: const EdgeInsets.all(8.0),
                            onConfirm: (Picker picker, List value) {
                              XLogger.info('value: ${value}');
                              XLogger.info('picker.getSelectedValues(): ${picker.getSelectedValues()}');
                              setState(() {
                                modeOptionsIndex1 = value[0];
                              });
                              if (switchValue == 0) {
                                onSendCommandClickCallback(getCommand());
                              }
                            },
                          );
                          picker.selecteds = [modeOptionsIndex1];
                          picker.showModal(context);
                        },
                        child: Text(
                          '${modeOptions1[modeOptionsIndex1].label}',
                          style: TextStyle(fontSize: 16, color: AppTheme.themeConfig.primaryColor),
                        )),
                  ],
                ),
                // 分割线
                const Divider(
                  height: 20,
                  thickness: 1,
                  color: Color(0xffe5e5e5),
                ),
                // Row(
                //   children: [
                //     Expanded(
                //       child: Text(
                //         '省电模式',
                //         style: TextStyle(
                //           fontSize: 18,
                //           color: AppTheme.themeConfig.primaryTextColor,
                //           fontWeight: FontWeight.bold,
                //         ),
                //       ),
                //     ),
                //     // 单选框
                //     Radio(
                //       value: 1,
                //       groupValue: switchValue,
                //       onChanged: (value) {
                //         XLogger.info('value: $value');
                //         setState(() {
                //           switchValue = value!;
                //         });
                //         kaiji();
                //
                //       },
                //       activeColor: AppTheme.themeConfig.primaryColor,
                //     ),
                //   ],
                // ),
                // Row(
                //   children: [
                //     // 提示语
                //     Expanded(
                //       child: Text(
                //         '每1小时自动更新位置，续航时间长，会影响历史轨迹的精确度。',
                //         style: TextStyle(
                //           fontSize: 16,
                //           color: AppTheme.themeConfig.infoTextColor,
                //         ),
                //       ),
                //     ),
                //   ],
                // ),
                // // 分割线
                // const Divider(
                //   height: 20,
                //   thickness: 1,
                //   color: Color(0xffe5e5e5),
                // ),
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        '关闭定位模式',
                        style: TextStyle(
                          fontSize: 18,
                          color: AppTheme.themeConfig.primaryTextColor,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    Radio(
                      value: 2,
                      groupValue: switchValue,
                      onChanged: (value) {
                        XLogger.info('value: $value');
                        setState(() {
                          switchValue = value!;
                        });
                        onSendCommandClickCallback(getCommand());
                      },
                      activeColor: AppTheme.themeConfig.primaryColor,
                    ),
                  ],
                ),
                Row(
                  children: [
                    // 提示语
                    Expanded(
                      child: Text(
                        '关闭定位模式后不能定位，没有轨迹，可提高拾音续航时间',
                        style: TextStyle(
                          fontSize: 16,
                          color: AppTheme.themeConfig.infoTextColor,
                        ),
                      ),
                    ),
                  ],
                ),
                // Row(
                //     mainAxisAlignment:  MainAxisAlignment.center,
                //   children: [
                //     Expanded(child:  TextButton(
                //       onPressed: () {
                //         Navigator.pop(context);
                //       },
                //       child: const Text(
                //         '取消',
                //         textAlign: TextAlign.center,
                //         style: TextStyle(color: Colors.grey, fontSize: 15),
                //       ),
                //     ),
                //     ),
                //     Expanded(child:
                //     TextButton(
                //       onPressed: () {
                //         // 发送指令
                //         // Navigator.pop(context);
                //         _onSendCommandClickCallback(getCommand());
                //       },
                //       child: Text(
                //         '发送指令',
                //         textAlign: TextAlign.center,
                //         style: TextStyle(color: AppTheme.themeConfig.primaryColor, fontSize: 15),
                //       ),
                //     ),
                //     ),
                //
                //   ],
                // ),
              ],
            ),
          ),
        ));
  }
  _kaitongmiaoding() {
    /// 自定义一个弹窗
    showGeneralDialog(
      context: context,
      pageBuilder: (BuildContext buildContext, Animation<double> animation, Animation<double> secondaryAnimation) {

        return Dialog(
          child: Container(
            height: 200,
            width: 300,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(16),
                color: AppTheme.themeConfig.greyBgColor
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const SizedBox(height: 1),
                const Text(
                  '您还没开通秒定模式',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(height: 10),
                SizedBox(
                  width: 220, // 设置按钮宽度
                  height: 40, // 设置按钮高度
                  child: TextButton(
                    style: TextButton.styleFrom(
                      minimumSize: const Size(100, 40),
                      backgroundColor: AppTheme.themeConfig.primaryColor, // 设置背景色为蓝色
                      foregroundColor: Colors.white, // 设置文字颜色为白色，增强对比度
                      textStyle: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    onPressed: () {
                      _goToVipPage("3");
                      Navigator.pop(context);
                    },
                    child: const Text('前往开通'),
                  ),
                ),

                SizedBox(
                  width: 220, // 设置按钮宽度
                  height: 40, // 设置按钮高度
                  child: TextButton(
                    style: TextButton.styleFrom(
                      minimumSize: const Size(100, 40),
                      backgroundColor: AppTheme.themeConfig.infoTextColor, // 设置背景色为蓝色
                      foregroundColor: Colors.white, // 设置文字颜色为白色，增强对比度
                      textStyle: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: const Text('取消'),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
  _goToVipPage(String chooseTabIndex) {
    context.push('${RouterManager.vipService}?chooseTabIndex=${chooseTabIndex}').then((value){
      getDeviceInfo();
    });
  }
  setDevice({required dynamic data, VoidCallback? voidCallback}) async {
    XLogger.info(data);
    XLogger.info('${deviceDetails?.deviceName}');
    if (deviceDetails?.securityVip == 1) {
    } else {}

    ToastUtils.showLoading(status: "处理中...");
    final res =
    await post<ReadFileResp, ReadFileResp>('$newBaseULr/device/command',
        data: data,
        decodeType: ReadFileResp());
    res.when(success: (resp) async {
      if(voidCallback != null){
        voidCallback();
      }
    }, failure: (String msg, int code) {
      ToastUtils.dismissLoading();
      XLogger.error('设备录音文件已读失败：msg: $msg, code: $code');
      return ReadFileResp();
    });
  }
}
